Page({
  data: {
    searchValue: '',
    showAddressInfo: true, // 控制地址信息条是否显示
    selectedAddress: {
      name: "张三",
      phone: "18812345678",
      province: "浙江省",
      city: "杭州市",
      district: "西湖区",
      detailInfo: "文三路198号"
    },
    categories: [
      { id: 0, name: "人气TOP" },
      { id: 1, name: "奶茶系列" },
      { id: 2, name: "果茶系列" },
      { id: 3, name: "芝士系列" },
      { id: 4, name: "小吃系列" },
      { id: 5, name: "甜品系列" }
    ],
    products: [
      {
        categoryId: 0,
        items: [
          { id: 101, name: "招牌奶茶", desc: "传统手工制作", price: 18, sales: 232, imageUrl: "/images/products/product1.jpg" },
          { id: 102, name: "芝芝芒果", desc: "清新芒果配芝士", price: 22, sales: 188, imageUrl: "/images/products/product2.jpg" },
          { id: 103, name: "多肉葡萄", desc: "多种水果搭配", price: 20, sales: 120, imageUrl: "/images/products/product3.jpg" }
        ]
      },
      {
        categoryId: 1,
        items: [
          { id: 104, name: "烤奶", desc: "香浓奶香回味", price: 19, sales: 166, imageUrl: "/images/products/product4.jpg" },
          { id: 105, name: "波波奶茶", desc: "珍珠与奶茶的完美结合", price: 18, sales: 155, imageUrl: "/images/products/product1.jpg" },
          { id: 106, name: "黑糖奶茶", desc: "黑糖与奶茶的碰撞", price: 20, sales: 143, imageUrl: "/images/products/product4.jpg" }
        ]
      },
      {
        categoryId: 2,
        items: [
          { id: 107, name: "满杯红柚", desc: "新鲜红柚肉", price: 22, sales: 125, imageUrl: "/images/products/product5.jpg" },
          { id: 108, name: "芒果果茶", desc: "清新芒果口感", price: 21, sales: 132, imageUrl: "/images/products/product2.jpg" },
          { id: 109, name: "满杯橙子", desc: "维C充沛", price: 23, sales: 112, imageUrl: "/images/products/product5.jpg" }
        ]
      },
      {
        categoryId: 3,
        items: [
          { id: 110, name: "芝士奶盖奶茶", desc: "浓郁奶盖", price: 21, sales: 145, imageUrl: "/images/products/product3.jpg", tag: "热门" },
          { id: 111, name: "芝士奶盖绿茶", desc: "清爽绿茶", price: 20, sales: 134, imageUrl: "/images/products/product6.jpg" },
          { id: 112, name: "芝士草莓", desc: "草莓融芝士", price: 25, sales: 120, imageUrl: "/images/products/product5.jpg" }
        ]
      },
      {
        categoryId: 4,
        items: [
          { id: 113, name: "盐酥鸡", desc: "外酥里嫩", price: 18, sales: 208, imageUrl: "/images/products/product4.jpg" },
          { id: 114, name: "薯条", desc: "香脆可口", price: 16, sales: 195, imageUrl: "/images/products/product1.jpg" },
          { id: 115, name: "鸡米花", desc: "香辣多汁", price: 17, sales: 176, imageUrl: "/images/products/product3.jpg" }
        ]
      },
      {
        categoryId: 5,
        items: [
          { id: 116, name: "草莓波波", desc: "新鲜草莓搭配珍珠", price: 23, sales: 102, imageUrl: "/images/products/product5.jpg", tag: "新品" },
          { id: 117, name: "芒果双皮奶", desc: "顺滑双皮奶", price: 20, sales: 98, imageUrl: "/images/products/product2.jpg" },
          { id: 118, name: "抹茶蛋糕", desc: "松软可口", price: 22, sales: 87, imageUrl: "/images/products/product6.jpg" }
        ]
      }
    ],
    activeCategory: 0,
    scrollIntoView: 'category0',
    cartCount: 0,
    cart: [],
    showCartDetail: false, // 控制购物车小框是否显示
    addedProduct: null, // 刚添加的商品信息
    deliveryFee: 6, // 配送费用
    freeDeliveryThreshold: 30, // 免配送费阈值
    categoryTops: [] // 存储每个分类的顶部位置
  },

  onLoad: function (options) {
    // 从缓存获取选中的地址
    const selectedAddress = wx.getStorageSync('selectedAddress');
    if (!selectedAddress) {
      // 如果没有选择地址，则返回地址选择页面
      wx.navigateTo({
        url: '/pages/delivery-address/delivery-address'
      });
      return;
    }

    // 从缓存中获取购物车数据
    const cartList = wx.getStorageSync('cartList') || [];
    this.setData({
      selectedAddress: selectedAddress,
      cart: cartList,
      cartCount: cartList.reduce((total, item) => total + (item && item.quantity ? item.quantity : 0), 0)
    });

    // 计算每个分类的顶部位置（用于滚动定位）
    this.calculateCategoryTops();
  },

  onShow: function () {
    // 更新选中的地址（可能在其他页面修改了）
    const selectedAddress = wx.getStorageSync('selectedAddress');
    if (selectedAddress) {
      this.setData({ selectedAddress });
    }

    // 每次显示页面时更新购物车数据
    const cartList = wx.getStorageSync('cartList') || [];
    this.setData({
      cart: cartList,
      cartCount: cartList.reduce((total, item) => total + (item && item.quantity ? item.quantity : 0), 0)
    });
  },

  // 搜索输入处理
  onSearch: function (e) {
    this.setData({
      searchValue: e.detail.value
    });
    // 可以在这里实现实时搜索功能
  },

  // 清除搜索内容
  clearSearch: function () {
    this.setData({
      searchValue: ''
    });
  },

  // 修改收货地址
  changeAddress: function () {
    wx.navigateTo({
      url: '/pages/delivery-address/delivery-address'
    });
  },

  // 切换分类
  switchCategory: function (e) {
    const categoryId = e.currentTarget.dataset.id;
    this.setData({
      activeCategory: categoryId,
      scrollIntoView: 'category' + categoryId
    });
  },

  // 滚动处理
  handleScroll: function (e) {
    const scrollTop = e.detail.scrollTop;
    const categoryTops = this.data.categoryTops || [];

    // 根据滚动位置判断当前是哪个分类
    for (let i = categoryTops.length - 1; i >= 0; i--) {
      if (scrollTop >= categoryTops[i].top - 10) { // 减去一个偏移值，使体验更好
        if (this.data.activeCategory !== categoryTops[i].id) {
          this.setData({
            activeCategory: categoryTops[i].id
          });
        }
        break;
      }
    }
  },

  // 计算各分类区域的顶部位置
  calculateCategoryTops: function () {
    const query = wx.createSelectorQuery();
    query.selectAll('.category-title').boundingClientRect(rects => {
      const categoryTops = rects.map(rect => {
        return {
          id: parseInt(rect.id.replace('category', '')),
          top: rect.top
        };
      });
      this.setData({ categoryTops: categoryTops });
    }).exec();
  },

  // 跳转到商品详情
  toDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}&from=delivery`
    });
  },

  // 添加到购物车
  addToCart: function (e) {
    try {
      const { id, name, price, imageurl } = e.currentTarget.dataset;

      // 构建商品信息
      const productInfo = {
        id: parseInt(id),
        name: name || '',
        price: parseFloat(price) || 0,
        image: imageurl || '/images/products/default.jpg',
        quantity: 1,
        itemTotal: parseFloat(price) || 0
      };

      // 获取购物车
      const cartList = [...(this.data.cart || [])];
      let found = false;
      let updatedProduct = null;

      // 查找购物车中是否已有该商品
      if (cartList && cartList.length > 0) {
        for (let i = 0; i < cartList.length; i++) {
          if (cartList[i] && cartList[i].id === parseInt(id)) {
            found = true;
            cartList[i].quantity = (cartList[i].quantity || 0) + 1;
            cartList[i].itemTotal = cartList[i].quantity * parseFloat(price || 0);
            updatedProduct = cartList[i];
            break;
          }
        }
      }

      // 如果购物车中没有该商品，则添加
      if (!found) {
        cartList.push(productInfo);
        updatedProduct = productInfo;
      }

      // 计算购物车总数量
      const cartCount = cartList.reduce((total, item) =>
        total + (item && typeof item.quantity === 'number' ? item.quantity : 0), 0);

      // 更新数据
      this.setData({
        cart: cartList,
        cartCount: cartCount,
        addedProduct: updatedProduct,
        showCartDetail: true
      });

      // 保存到本地存储
      wx.setStorageSync('cartList', cartList);

      // 3秒后隐藏购物车小框
      setTimeout(() => {
        this.setData({
          showCartDetail: false
        });
      }, 3000);

    } catch (error) {
      console.error('添加到购物车出错:', error);
      wx.showToast({
        title: '添加失败，请重试',
        icon: 'none'
      });
    }
  },

  // 跳转到购物车页面
  toCart: function () {
    wx.switchTab({
      url: '/pages/cart/cart'
    });
  },

  // 更新小框中商品数量
  updateQuantity: function (e) {
    const { operation } = e.currentTarget.dataset;
    const { addedProduct, cart } = this.data;

    if (!addedProduct) return;

    let quantity = addedProduct.quantity || 1;

    if (operation === 'add') {
      quantity += 1;
    } else if (operation === 'minus') {
      if (quantity <= 1) return;
      quantity -= 1;
    }

    // 更新购物车中的商品数量
    const newCart = Array.isArray(cart) ? cart.map(item => {
      if (item && item.id === parseInt(addedProduct.id)) {
        const updatedItem = { ...item, quantity };
        // 重新计算总价
        updatedItem.itemTotal = (updatedItem.price || 0) * quantity + this.getAddonPrice(updatedItem);
        return updatedItem;
      }
      return item;
    }) : [];

    this.setData({
      cart: newCart,
      cartCount: newCart.reduce((total, item) => total + (item && item.quantity ? item.quantity : 0), 0),
      'addedProduct.quantity': quantity
    });

    // 保存到本地存储
    wx.setStorageSync('cartList', newCart);
  },

  // 计算加料的总价格
  getAddonPrice(item) {
    if (!item || !item.addon || !Array.isArray(item.addon) || item.addon.length === 0) return 0;
    return item.addon.reduce((sum, addon) => sum + (addon && addon.price ? parseFloat(addon.price) : 0), 0);
  },

  // 关闭购物车小框
  closeCartDetail: function () {
    this.setData({
      showCartDetail: false
    });
  },

  // 关闭地址信息条
  closeAddressInfo: function () {
    this.setData({
      showAddressInfo: false
    });
  },

  // 停止事件冒泡
  stopPropagation: function (e) {
    // 用于阻止点击事件冒泡
  },

  // 判断配料是否已选择
  isAddonSelected: function (addonId) {
    return this.data.selectedSpecs.addon.some(item => item.id === addonId);
  }
}) 